//
//  BalanceDetailViewController.swift
//  ShareCar
//
//  Created by lishuai on 2018/8/31.
//  Copyright © 2018年 changqingkeji. All rights reserved.
//

import UIKit

class BalanceDetailViewController: UITableViewController {

    var dataSource = [User.BalanceDetail.Item]()
    var pagex: Int = 1            //默认请求第一页

    override func viewDidLoad() {
        super.viewDidLoad()
        
        let header = CustomRefreshHeader()
        tableView.gtm_addRefreshHeaderView(refreshHeader: header) { [weak self] in
            self?.requestData(isMore: true)
        }
        
        let footer = CustomRefreshFooter()
        tableView.gtm_addLoadMoreFooterView(loadMoreFooter: footer) { [weak self] in
            self?.requestData(isMore: false)
        }
        //立即刷新
        tableView.triggerRefreshing()
    }
    
    func requestData(isMore: Bool) {
        
        pagex = isMore ? 1 : pagex + 1
        JZLoading.showLoadingWith(toView: self.view)
        
        User.balanceDetail(page: pagex, pageSize: 10, success: { [weak self] data in
            
            JZLoading.hideLoading()
            self?.tableView.endRefreshing(isSuccess: true)
            
            if let data = data, let self = self {
                self.dataSource = isMore ? data.list : self.dataSource + data.list
                
                UIView.removeStatusView()
                self.tableView.reloadData()
                
                if self.dataSource.count == 0 {
                    UIView.showInfoViewWithEmpty(self.view, text: "暂无明细")
                    return
                }
            }
        }) { [weak self] error in
            self?.tableView.endRefreshing(isSuccess: true)
            JZLoading.hideLoading()
            self?.showError(error)
        }
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
    }

    // MARK: - Table view data source

    override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return dataSource.count
    }

    override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: "reuseIdentifier", for: indexPath)

        if let cell = cell as? BalanceDetailCell {
            cell.setup(item: dataSource[indexPath.row])
        }
        return cell
    }
    
    override func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        return 70
    }
}
